package crm.view.tree.verwaltung;

import java.util.ArrayList;

import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

import crm.model.teacherPC.CRMListener;
import crm.model.teacherPC.Manager;
import crm.model.teacherPC.net.StudentPC;



public class StudentTreeModel extends DefaultTreeModel implements CRMListener{
	Manager manager;
	ArrayList<TreeModelListener> listener;
	public StudentTreeModel(Manager manager){
		super(new DefaultMutableTreeNode(manager));
		this.manager=manager;
		listener = new ArrayList<TreeModelListener>();
		manager.addListener(this);

	}

	public Object getChild(Object obj, int i) {
		if (obj instanceof Manager){
			return manager.getStudent(i);
		}else if (obj instanceof StudentPC){
			StudentPC student = (StudentPC)obj;
			return student.getWindows().get(i);
		}else if (obj instanceof String){
			return obj;
		}
		return null;
	}

	public int getChildCount(Object obj) {
		if (obj instanceof Manager){
			return manager.getStudentCount();
		}else if (obj instanceof StudentPC){
			StudentPC student = (StudentPC)obj;
			return student.getWindows().size();
		}
		return 0;
	}

	public int getIndexOfChild(Object arg0, Object arg1) {
		return 0;
	}

	public Object getRoot() {
		return manager;
	}

	public boolean isLeaf(Object obj) {
		return getChildCount(obj) == 0;
	}



	public void removeTreeModelListener(TreeModelListener e) {
		listener.remove(e);
	}

	public void addTreeModelListener(TreeModelListener e) {
		listener.add(e);
	}

	public void fireTreeModelListener(StudentPC student){
		for (TreeModelListener l : listener) {
			l.treeStructureChanged(new TreeModelEvent(this, new Object[]{getRoot(), student}));
		}
	}
	public void fireTreeRemoveModelListener(StudentPC student){
		for (TreeModelListener l : listener) {
			l.treeNodesRemoved(new TreeModelEvent(this, new Object[]{getRoot(), student}));
		}
	}
	public void fireTreeModelListener(){
		for (TreeModelListener l : listener) {

			l.treeStructureChanged(new TreeModelEvent(this, new Object[]{getRoot()}));
		}
	}



	public void actualisingComplete(StudentPC student) {
		fireTreeModelListener(student);
	}


	public void valueForPathChanged(TreePath path, Object newValue) {
		System.out.println(path + " : " + newValue);

	}

	@Override
	public void connectionClosed() {
		// TODO Auto-generated method stub

	}

	@Override
	public void connectionStarted() {
		fireTreeModelListener();
	}

	@Override
	public void exitCRM() {
		// TODO Auto-generated method stub

	}

	@Override
	public void studentAdded(StudentPC student) {
		fireTreeModelListener(student);

	}

	@Override
	public void studentRemoved(StudentPC student) {
		fireTreeRemoveModelListener(student);

	}


}
